﻿Imports System
Imports System.Workflow.ComponentModel

Namespace System.Workflow.Runtime
    Friend Class ContextActivityUtils
        ' Methods
        Friend Shared Function ContextActivity(ByVal activity As Activity) As Activity
            Dim parent As Activity = activity
            Do While ((Not parent Is Nothing) AndAlso (parent.GetValue(Activity.ActivityExecutionContextInfoProperty) Is Nothing))
                parent = parent.Parent
            Loop
            Return parent
        End Function

        Friend Shared Function ContextId(ByVal activity As Activity) As Integer
            Return DirectCast(ContextActivityUtils.ContextActivity(activity).GetValue(Activity.ActivityExecutionContextInfoProperty), ActivityExecutionContextInfo).ContextId
        End Function

        Friend Shared Function ParentContextActivity(ByVal activity As Activity) As Activity
            Dim info As ActivityExecutionContextInfo = DirectCast(ContextActivityUtils.ContextActivity(activity).GetValue(Activity.ActivityExecutionContextInfoProperty), ActivityExecutionContextInfo)
            If (info.ParentContextId = -1) Then
                Return Nothing
            End If
            Return ContextActivityUtils.RetrieveWorkflowExecutor(activity).GetContextActivityForId(info.ParentContextId)
        End Function

        Friend Shared Function RetrieveWorkflowExecutor(ByVal activity As Activity) As WorkflowExecutor
            Dim executor As WorkflowExecutor = Nothing
            Dim parent As Activity = activity
            Do While ((Not parent Is Nothing) AndAlso (Not parent.Parent Is Nothing))
                parent = parent.Parent
            Loop
            If (Not parent Is Nothing) Then
                executor = DirectCast(parent.GetValue(WorkflowExecutor.WorkflowExecutorProperty), WorkflowExecutor)
            End If
            Return executor
        End Function

        Friend Shared Function RootContextActivity(ByVal activity As Activity) As Activity
            Return ContextActivityUtils.RetrieveWorkflowExecutor(activity).RootActivity
        End Function

    End Class
End Namespace

